<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '需求单',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view style="display: flex; flex-direction: column; height: 100vh; background-color: #f2f2f1">
    <view style="position: sticky; top: 0; z-index: 9999">
      <wd-navbar
        :title="`${form.cusFlag == '1' ? '非客户' : '客户'}需求单`"
        :bordered="false"
        safeAreaInsetTop
      >
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
        <template #right>
          <th-print v-if="form.id" :data="{ ...form }"></th-print>
          <!-- <view class="print">
            <view class="icon" @click="showPrinter">
              <wd-icon name="print" size="22px" color="white"></wd-icon>
              打印
            </view>
            <view class="list" v-if="printerVisible">
              <view>
                <uni-print-button
                  size="small"
                  class="btn"
                  type="text"
                  kind="demand"
                  :data="[{ ...form }]"
                >
                  来样打印
                </uni-print-button>
              </view>
              <view>
                <uni-print-button
                  size="small"
                  class="btn"
                  type="text"
                  kind="demand"
                  :data="[{ ...form }]"
                >
                  送样打印
                </uni-print-button>
              </view>
            </view>
          </view> -->
        </template>
      </wd-navbar>
    </view>
    <view style="display: flex; flex: 1; flex-direction: column; height: 0">
      <view style="flex: 1; overflow: auto">
        <wd-form ref="formRef" :model="form" :rules="rules">
          <th-card title="基础信息">
            <!-- <th-form> -->
            <th-form-item label="单据编号">
              <view class="text seq-no-text">
                {{ form.demandCode }}
                <!-- <wd-icon
                      name="refresh1"
                      color="#9d9595"
                      style="margin-right: 4rpx"
                      @click="getDemandCode('need_demandCode')"
                    ></wd-icon> -->
              </view>
            </th-form-item>
            <th-form-item label="日期">
              <view class="text seq-no-text">
                <wd-datetime-picker
                  prop="demandDate"
                  type="date"
                  v-model="form.demandDate"
                  label=""
                  :minDate="minDate"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                ></wd-datetime-picker>
              </view>
            </th-form-item>
            <th-form-item label="客户" v-if="form.cusFlag == '0'" class="form-demandDesc">
              <!-- <wd-input type="text" v-model="form.cusName" placeholder="" no-border /> -->
              <view class="text seq-no-text" @click="showSelectPickerCompany">
                <template
                  v-if="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                >
                  {{ form.cusName }}
                </template>
                <template v-else>
                  <wd-input
                    type="text"
                    prop="cusName"
                    readonly
                    v-model="form.cusName"
                    placeholder="请选择客户"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </template>
              </view>
            </th-form-item>
            <th-form-item :label="form.cusFlag == '0' ? '业务员' : '需求人'">
              <view class="text seq-no-text" @click="showSelectUser">
                <wd-input
                  type="text"
                  readonly
                  prop="personName"
                  v-model="form.personName"
                  :placeholder="`请选择${form.cusFlag == '0' ? '业务员' : '需求人'}`"
                  no-border
                />
              </view>
            </th-form-item>
            <th-form-item label="业务部门" v-if="form.cusFlag == '0'">
              <text class="text seq-no-text">{{ form.deptName }}</text>
            </th-form-item>
            <th-form-item label="所属公司" v-if="form.cusFlag == '0'">
              <text class="text seq-no-text">{{ form.tenantName }}</text>
            </th-form-item>
            <th-form-item label="项目名称" v-if="form.petitionName">
              <text class="text seq-no-text">{{ form.petitionName }}</text>
            </th-form-item>
            <!-- </th-form> -->
          </th-card>
          <th-card title="产品需求信息">
            <th-form-item label="需求类型">
              <!-- <wd-picker
                    :columns="demandTypeList"
                    label=""
                    v-model="form.demandTypeCode"
                    label-key="demandName"
                    value-key="id"
                    prop="demandType"
                    placeholder="请选择需求类型"
                    @confirm="changedemandType"
                    :disabled="
                      form.taskId ||
                      !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                    "
                  ></wd-picker> -->

              <wd-col-picker
                label=""
                v-model="demandTypeCodeList"
                :columns="demandTypeCascader"
                value-key="value"
                label-key="label"
                style="width: 100%"
                :column-change="columnChangedemandTypeCodeList"
                @confirm="handleConfirmdemandTypeCodeList"
                :display-format="displayFormat"
                :readonly="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              ></wd-col-picker>
            </th-form-item>
            <th-form-item label="需求产品">
              <wd-input
                type="text"
                v-model="form.invName"
                prop="invName"
                placeholder="请输入需求产品"
                no-border
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
                use-suffix-slot
                style="width: 100%"
                @change="changeInv"
                clearable
              >
                <template
                  #suffix
                  v-if="
                    !(
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    )
                  "
                >
                  <wd-icon
                    name="search"
                    size="16px"
                    color="#bfbfbf"
                    @click="searchInvList"
                  ></wd-icon>
                </template>
              </wd-input>
            </th-form-item>
            <th-form-item label="需求产品规格">
              <wd-input
                type="text"
                v-model="form.invStd"
                prop="invStd"
                placeholder="请输入需求产品规格"
                no-border
                style="width: 100%"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              />
            </th-form-item>
            <th-form-item label="产品英文名称" v-if="form.cusFlag == '0'">
              <wd-input
                type="text"
                v-model="form.invEnName"
                prop="invEnName"
                placeholder="请输入产品英文名称"
                no-border
                style="width: 100%"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              />
            </th-form-item>
            <th-form-item label="用途" class="form-demandDesc">
              <wd-select-picker
                label=""
                v-model="form.applicationList"
                :columns="applicationTypeList"
                value-key="label"
                label-key="value"
                @confirm="getApplicationType"
                size="small"
                prop="applicationType"
                placeholder="请选择用途"
                filterable
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              ></wd-select-picker>
            </th-form-item>
            <th-form-item label="年需求量/吨" v-if="form.cusFlag == '0'">
              <wd-input
                type="number"
                v-model="form.invDemand"
                prop="invDemand"
                placeholder="请输入年需求量/吨"
                no-border
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              />
            </th-form-item>
            <th-form-item label="是否有外来样" v-if="form.cusFlag == '0'">
              <!-- <wd-input type="text" v-model="form.sampleFlagName" placeholder="" no-border /> -->
              <wd-picker
                :columns="samplaFlagList"
                label=""
                v-model="form.sampleFlag"
                @confirm="changesampleFlagName"
                prop="sampleFlag"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              />
            </th-form-item>
            <th-form-item
              label="外来样样品编码"
              v-if="form.sampleFlag != '0' && form.sampleFlag != null"
            >
              <view class="text seq-no-text">
                {{ form.sampleCode }}
                <wd-icon
                  name="refresh1"
                  color="#9d9595"
                  style="margin-right: 4rpx"
                  @click="getDemandCode('need_sampleCode')"
                ></wd-icon>
              </view>
            </th-form-item>
            <th-form-item
              label="外来样样品数量"
              v-if="form.sampleFlag != '0' && form.sampleFlag != null"
            >
              <view class="seq-no-text">
                <view style="flex: 1">
                  <wd-input
                    type="number"
                    v-model="form.samplesNum"
                    prop="samplesNum"
                    placeholder="请输入外来样样品数量"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </view>
                <view>
                  <wd-picker
                    :columns="sampleUnitList"
                    label=""
                    placeholder="请选择单位"
                    v-model="form.sampleUnit"
                    @confirm="getSampleUnit"
                    size="mini"
                    custom-class="sample-unit-class"
                    custom-value-class="sample-unit-custom-value-class"
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </view>
                <!-- <text v-if="form.sampleUnit" @click="getSampleUnit">{{ form.sampleUnit }}</text>
                <text v-else style="font-size: 28rpx; color: #9d9999" @click="getSampleUnit">请选择单位</text> -->
              </view>
            </th-form-item>
            <th-form-item
              label="外来样批次"
              v-if="form.sampleFlag != '0' && form.sampleFlag != null"
            >
              <view class="text seq-no-text">
                {{ form.sampleBatch }}
                <wd-icon
                  name="refresh1"
                  color="#9d9595"
                  style="margin-right: 4rpx"
                  @click="getDemandCode('need_sampleBatch')"
                ></wd-icon>
              </view>
            </th-form-item>
            <th-form-item label="要求完成时间">
              <wd-datetime-picker
                type="date"
                v-model="form.askCompleteTime"
                label=""
                prop="askCompleteTime"
                :minDate="minDate"
                placeholder="请选择要求完成时间"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              ></wd-datetime-picker>
            </th-form-item>
            <!--     v-if="
                form.demandTypeCode == '21' ||
                form.demandTypeCode == '22' ||
                form.demandTypeCode == '11'
              " -->
            <th-form-item label="是否给客户提供样品" v-if="form.cusFlag == '0'">
              <!-- <wd-input type="text" v-model="form.sampleFlagName" placeholder="" no-border /> -->
              <wd-picker
                :columns="requestFlagList"
                label=""
                v-model="form.requestFlag"
                prop="requestFlag"
                @confirm="changeRequestFlag"
                :disabled="
                  form.taskId ||
                  !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                "
              />
            </th-form-item>
            <th-form-item label="给客户提供样品数量" v-if="form.requestFlag == 1">
              <!-- <wd-input
                    type="text"
                    v-model="form.requestNum"
                    prop="requestNum"
                    placeholder="请输入给客户提供样品数量"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                    "
                  /> -->

              <view class="seq-no-text">
                <view style="flex: 1">
                  <wd-input
                    type="number"
                    v-model="form.requestNum"
                    prop="requestNum"
                    placeholder="请输入给客户提供样品数量"
                    no-border
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </view>
                <view>
                  <wd-picker
                    :columns="sampleUnitList"
                    label=""
                    placeholder=" "
                    v-model="form.requestNumUnit"
                    @confirm="getRequestNumUnit"
                    size="mini"
                    custom-class="sample-unit-class"
                    custom-value-class="sample-unit-custom-value-class"
                    :disabled="
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    "
                  />
                </view>
              </view>
            </th-form-item>
            <th-form-item label="附件" class="form-demandDesc form-file">
              <view class="form-file-view">
                <view
                  v-for="(file, index) in form.rdDemandFileEntity"
                  :key="file.fileUrl"
                  class="info-row-item"
                >
                  <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
                  <wd-icon
                    name="close-outline"
                    size="22px"
                    color="red"
                    @click.stop="removeFile(index)"
                    v-if="
                      !(
                        form.taskId ||
                        !(
                          form.status == 0 ||
                          form.status == null ||
                          form.status == 3 ||
                          form.status == 9
                        )
                      )
                    "
                  ></wd-icon>
                </view>
                <uploadFile
                  v-if="
                    !(
                      form.taskId ||
                      !(
                        form.status == 0 ||
                        form.status == null ||
                        form.status == 3 ||
                        form.status == 9
                      )
                    )
                  "
                  @complete="uploadComplete"
                ></uploadFile>
              </view>
            </th-form-item>
            <th-form-item label="需求描述" class="form-demandDesc">
              <view style="width: 100%">
                <wd-textarea
                  v-model="form.demandDesc"
                  placeholder="请填写需求描述"
                  auto-height
                  :maxlength="2000"
                  show-word-limit
                  no-border
                  prop="demandDesc"
                  :disabled="
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  "
                />
              </view>
            </th-form-item>
          </th-card>

          <template
            v-if="!(form.rdReplyChecksEntityReport && form.rdReplyChecksEntityReport.length)"
          >
            <th-card title="需求指标" v-if="isShowCheckTarget && form.standardByReview != 1">
              <wd-button
                :round="false"
                style="margin-bottom: 20rpx"
                @click="addCheckTargetList"
                type="text"
                v-if="
                  !(
                    form.taskId ||
                    !(
                      form.status == 0 ||
                      form.status == null ||
                      form.status == 3 ||
                      form.status == 9
                    )
                  )
                "
              >
                增行
              </wd-button>
              <view style="overflow: auto" class="table-container">
                <table class="analysis-table">
                  <tbody>
                    <tr>
                      <th style="width: 320rpx; min-width: 9.5rem">检验指标名称</th>
                      <th
                        style="width: 280rpx; min-width: 280rpx"
                        v-if="form.demandTypeCode != '42' && form.demandTypeCode != '12'"
                      >
                        U8指标
                      </th>
                      <th style="width: 280rpx; min-width: 280rpx">客户指标</th>
                      <th style="width: 280rpx; min-width: 280rpx">描述</th>
                      <th
                        style="width: 280rpx; min-width: 280rpx"
                        v-if="
                          !(
                            form.taskId ||
                            !(
                              form.status == 0 ||
                              form.status == null ||
                              form.status == 3 ||
                              form.status == 9
                            )
                          )
                        "
                      >
                        操作
                      </th>
                    </tr>
                    <!--    item.checktarget != item.cusCheckTarget ||
                      !(item.cusCheckTarget === null && item.cusCheckTarget === '') -->
                    <tr
                      align="center"
                      v-for="(item, index) in checkTargetList"
                      :key="index"
                      :class="[item.checktarget != item.cusCheckTarget ? 'line-red' : '']"
                    >
                      <td>
                        <view
                          v-if="
                            form.taskId ||
                            !(
                              form.status == 0 ||
                              form.status == null ||
                              form.status == 3 ||
                              form.status == 9
                            )
                          "
                        >
                          {{ item.cchkguidename }}
                        </view>
                        <view v-else>
                          <!-- <wd-input
                          v-model="item.cchkguidename"
                          clearable
                          no-border
                          style="background-color: transparent"
                          placeholder="请输入检验指标名称"
                          :disabled="item.addFlag == 0"
                        ></wd-input> -->
                          <view @click.stop="clickcchkguidename(item, index)" style="width: 100%">
                            <!-- <wd-input
                            v-model="item.cchkguidename"
                            clearable
                            no-border
                            style="background-color: transparent"
                            placeholder="请输入检验指标名称"
                            :disabled="item.addFlag == 0"
                          ></wd-input> -->
                            <text v-if="item.cchkguidename">{{ item.cchkguidename }}</text>
                            <text v-else style="color: #e3e3e3">请选择检验指标名称</text>
                            <!-- {{ item.cchkguidename || '请选择检验指标名称' }} -->
                          </view>
                        </view>
                      </td>
                      <td v-if="form.demandTypeCode != '42' && form.demandTypeCode != '12'">
                        <!-- <wd-input
                        v-model="item.checktarget"
                        clearable
                        no-border
                        style="background-color: transparent"
                        placeholder=" "
                        disabled
                      ></wd-input> -->
                        {{ item.checktarget }}
                      </td>
                      <td>
                        <view
                          v-if="
                            form.taskId ||
                            !(
                              form.status == 0 ||
                              form.status == null ||
                              form.status == 3 ||
                              form.status == 9
                            )
                          "
                        >
                          {{ item.cusCheckTarget }}
                        </view>
                        <template v-else>
                          <!-- <wd-input
                          v-model="item.cusCheckTarget"
                          clearable
                          no-border
                          style="background-color: transparent"
                          placeholder="请输入客户指标"
                        ></wd-input> -->
                          <wd-textarea
                            type="textarea"
                            v-model="item.cusCheckTarget"
                            placeholder="请输入客户指标"
                            style="background-color: transparent"
                            auto-height
                          ></wd-textarea>
                        </template>
                      </td>
                      <td>
                        <view
                          v-if="
                            form.taskId ||
                            !(
                              form.status == 0 ||
                              form.status == null ||
                              form.status == 3 ||
                              form.status == 9
                            )
                          "
                        >
                          {{ item.standardDesc }}
                        </view>
                        <template v-else>
                          <wd-textarea
                            type="textarea"
                            v-model="item.standardDesc"
                            placeholder="请输入描述"
                            style="background-color: transparent"
                            auto-height
                            :maxlength="255"
                          ></wd-textarea>
                        </template>
                      </td>

                      <td
                        v-if="
                          !(
                            form.taskId ||
                            !(
                              form.status == 0 ||
                              form.status == null ||
                              form.status == 3 ||
                              form.status == 9
                            )
                          )
                        "
                      >
                        <view>
                          <wd-button
                            :disabled="item.addFlag == 0"
                            type="text"
                            :style="{
                              color: item.addFlag == 0 ? 'gray' : 'red',
                            }"
                            @click="delRow(index, item)"
                          >
                            删除
                          </wd-button>
                        </view>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </view>
            </th-card>
          </template>
        </wd-form>

        <!-- <th-card
          title="需求指标"
          v-if="
            form.replyFlag == 1 &&
            form.rdReplyChecksEntityReport &&
            form.rdReplyChecksEntityReport.length
          "
        >
          <view style="overflow: auto" class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">检验指标名称</th>
                  <th style="width: 280rpx; min-width: 280rpx">客户指标</th>
                  <th style="width: 280rpx; min-width: 280rpx">检测结果</th>
                </tr>
                <tr
                  align="center"
                  v-for="(item, index) in form.rdReplyChecksEntityReport"
                  :key="index"
                >
                  <td>
                    <view>
                      {{ item.itemName }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.standardValuePm }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.itemValue }}
                    </view>
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card> -->

        <th-card
          v-if="form.reply && (form.reviewStatus == 2 || form.reviewStatus == 3)"
          title="需求评审"
        >
          <th-form-item label="回复" class="form-demandDesc">
            <text class="text">{{ form.reply }}</text>
          </th-form-item>
        </th-card>

        <th-card
          v-if="
            form.rdTaskFileEntity &&
            form.rdTaskFileEntity.length &&
            form.status == 2 &&
            (form.reviewStatus == 2 || form.reviewStatus == 3) &&
            form.wayCode == '4'
          "
          title="调查问卷回复附件"
        >
          <!-- <th-form-item label="回复" class="form-demandDesc">
              <text class="text">{{ form.reply }}</text>
            </th-form-item> -->

          <view class="info-list">
            <view class="info-list-main">
              <view class="info-list-row">
                <view class="info-list-label">附件</view>
                <view class="info-list-value">
                  <view style="display: flex; flex-direction: column">
                    <view
                      v-for="file in form.rdTaskFileEntity"
                      :key="file.id"
                      class="info-row-item"
                    >
                      <text @click="previewFileHandle(file.fileUrl)">
                        {{ file.fileName }}
                      </text>
                      <wd-icon
                        name="cloud-download"
                        size="22px"
                        @click="downloadFileHandle(file.fileUrl, file.fileName)"
                      ></wd-icon>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </th-card>

        <th-card
          title="交接列表"
          v-if="
            (form.reviewStatus == 2 || form.reviewStatus == 3) &&
            rdConnectEntityList.length &&
            form.status == 2
          "
        >
          <view style="overflow: auto" class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">样品批号</th>
                  <th style="width: 280rpx; min-width: 280rpx">样品数量</th>
                  <th style="width: 280rpx; min-width: 280rpx">移交时间</th>
                  <th style="width: 280rpx; min-width: 280rpx">交接时间</th>
                  <th style="width: 280rpx; min-width: 280rpx">样品接受人</th>
                  <th style="width: 280rpx; min-width: 280rpx">审核状态</th>
                </tr>
                <tr align="center" v-for="(item, index) in rdConnectEntityList" :key="index">
                  <td>
                    {{ item.sampleBatch }}
                  </td>
                  <td>
                    {{ item.sampleNum }}
                  </td>
                  <td>
                    {{ item.moveTime }}
                  </td>
                  <td>
                    {{ item.connectTime }}
                  </td>
                  <td>
                    {{ item.connectName }}
                  </td>
                  <td>
                    <!-- {{ item.status }} -->
                    <wd-tag
                      :bg-color="getStatus(item.status)['color']"
                      :color="getStatus(item.status)['color']"
                      plain
                    >
                      {{ getStatus(item.status)['label'] }}
                    </wd-tag>
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>

        <!-- <th-card
            title="实验报告信息"
            v-if="
              (form.reviewStatus == 2 || form.reviewStatus == 3) &&
              form.demandTypeCode == '42' &&
              experimentReportEntity &&
              experimentReportEntity.length
            "
          > -->
        <!-- <th-form>
              <th-form-item label="实验报告单号">
                <view class="text seq-no-text">
                  <wd-picker
                    :columns="experimentReportEntity"
                    label=""
                    v-model="reviewCode"
                    @confirm="reportreviewCode($event, 1)"
                    placeholder="请选择实验报告单号"
                    value-key="ccode"
                    label-key="ccode"
                  />
                </view>
              </th-form-item>
              <th-form-item label="产品名称">
                <view class="text seq-no-text">
                  {{ reportRevideData.invName }}
                </view>
              </th-form-item>
              <th-form-item label="产品规格">
                <view class="text seq-no-text">
                  {{ reportRevideData.invStd }}
                </view>
              </th-form-item>
              <th-form-item label="实验目的">
                <view class="text seq-no-text">
                  {{ reportRevideData.purpose }}
                </view>
              </th-form-item>
            </th-form> -->

        <!-- <view
          v-if="
            (form.reviewStatus == 2 || form.reviewStatus == 3) &&
            form.demandTypeCode == '42' &&
            experimentReportEntity &&
            experimentReportEntity.length
          "
        >
          <view v-if="reportRevideData.checkReportId" class="assay-report-content">
            <assayReport ref="fsReportDetailRef"></assayReport>
          </view>
        </view> -->
        <!-- </th-card> -->

        <th-card
          title="任务检验报告"
          v-if="
            form.replyFlag == 1 &&
            form.rdReplyChecksEntityTask &&
            form.rdReplyChecksEntityTask.length
          "
        >
          <view style="overflow: auto" class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">检测项目(分析手段)</th>
                  <th style="width: 280rpx; min-width: 280rpx">检测指标</th>
                  <th style="width: 280rpx; min-width: 280rpx">指标单位</th>
                  <th style="width: 280rpx; min-width: 280rpx">检测结果</th>
                  <th style="width: 480rpx; min-width: 480rpx">报告</th>
                </tr>
                <tr
                  align="center"
                  v-for="(item, index) in form.rdReplyChecksEntityTask"
                  :key="index"
                >
                  <td>
                    <view>
                      {{ item.analysisName }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.itemName }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.unit }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.itemValue }}
                    </view>
                  </td>
                  <td>
                    <view>
                      <template
                        v-if="
                          item.qcExoticAttachmentsEntity && item.qcExoticAttachmentsEntity.length
                        "
                      >
                        <view
                          v-for="file in item.qcExoticAttachmentsEntity"
                          @click="previewFileHandle(file.url)"
                          :key="file.id"
                          class="info-row-item"
                          style="text-align: left"
                        >
                          {{ file.name }}
                        </view>
                      </template>
                    </view>
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>

        <th-card
          :title="`${form.projectName || ''}终检报告`"
          v-if="
            form.replyFlag == 1 &&
            form.rdReplyChecksEntityReport &&
            form.rdReplyChecksEntityReport.length
          "
        >
          <view style="overflow: auto" class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">检测项目(分析手段)</th>
                  <th style="width: 280rpx; min-width: 280rpx">检测指标</th>
                  <th style="width: 280rpx; min-width: 280rpx">指标单位</th>
                  <th style="width: 280rpx; min-width: 280rpx">检测结果</th>
                  <th style="width: 480rpx; min-width: 480rpx">报告</th>
                </tr>
                <tr
                  align="center"
                  v-for="(item, index) in form.rdReplyChecksEntityReport"
                  :key="index"
                >
                  <td>
                    <view>
                      {{ item.analysisName }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.itemName }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.unit }}
                    </view>
                  </td>
                  <td>
                    <view>
                      {{ item.itemValue }}
                    </view>
                  </td>
                  <td>
                    <view>
                      <template
                        v-if="
                          item.qcMiddleAttachmentsEntity && item.qcMiddleAttachmentsEntity.length
                        "
                      >
                        <view
                          v-for="file in item.qcMiddleAttachmentsEntity"
                          @click="previewFileHandle(file.url)"
                          :key="file.id"
                          class="info-row-item"
                          style="text-align: left"
                        >
                          {{ file.name }}
                        </view>
                      </template>
                    </view>
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>

        <th-card
          title="需求回复确认"
          v-if="form.replyFlag == 1 && form.rdReplyFileEntity && form.rdReplyFileEntity.length"
        >
          <view class="form-file-view">
            <view
              v-for="(file, index) in form.rdReplyFileEntity"
              :key="file.fileUrl"
              class="info-row-item"
            >
              <text @click="previewFileHandle(file.fileUrl)">{{ file.fileName }}</text>
            </view>
          </view>
        </th-card>

        <th-card
          title="审核信息"
          v-if="form.status == '1' || form.status == '2' || form.status == '3'"
        >
          <view class="row-list">
            <view class="row" v-if="form.id && form.taskId">
              <!-- <view class="label">审核意见</view> -->
              <view class="value">
                <view class="mb2 mt2">
                  <h5>审核意见</h5>
                </view>
                <wd-textarea
                  type="textarea"
                  v-model="comment"
                  rows="6"
                  placeholder="请输入审核意见"
                  style="border: 1px solid #f7f7f7"
                ></wd-textarea>
              </view>
            </view>
            <view>
              <!-- <view class="mb2 mt2">
                    <h5>流转详情</h5>
                  </view> -->
              <!-- <flowDetailsTable
                    ref="flowDetailsTableRef"
                    :processInstanceId="form.instanceId"
                    :key="new Date().getTime()"
                  ></flowDetailsTable> -->
              <flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable>
            </view>
          </view>
        </th-card>

        <!-- <th-card v-if="form.taskFlag == 1" title="评审信息">
              <th-form-item label="需求评审结论" class="form-demandDesc">
                <text class="text">{{ form.demandResult }}</text>
              </th-form-item>
              <th-form-item label="评审结果">
                <text class="text">
                  <view v-if="form.rdFlag == '1'" class="result-tag">通过</view>
                  <view
                    v-else-if="form.rdFlag == '0'"
                    class="result-tag"
                    style="background-color: #f50"
                  >
                    不通过
                  </view>
                </text>
              </th-form-item>
              <th-form-item label="技术负责人">
                <text class="text">{{ form.technologyHeadName }}</text>
              </th-form-item>
              <th-form-item label="副总工">
                <wd-img
                  :width="200"
                  :height="100"
                  :src="form.deputyChiefEngineerUrl"
                  @click="preview(form.deputyChiefEngineerUrl)"
                />
              </th-form-item>
              <th-form-item label="总工">
                <wd-img
                  :width="200"
                  :height="100"
                  :src="form.chiefEngineerUrl"
                  @click="preview(form.chiefEngineerUrl)"
                />
              </th-form-item>
            </th-card> -->
      </view>

      <view class="flow-btn-fixed" v-if="form.id && form.taskId">
        <view class="btn_group" style="width: 100%">
          <view class="btn danger" @click="oncomplete(1)">
            <image src="../../../static/reject.png" class="btn-icon"></image>
            拒绝
          </view>
          <view class="btn primary" @click="oncomplete(0)">
            <image src="../../../static/tongyi.png" class="btn-icon"></image>
            同意
          </view>
        </view>
      </view>
      <view class="flow-btn-fixed" v-else>
        <view class="btn_group" style="width: 100%">
          <!-- <view class="btn danger" @click="onCancel()">取消</view> -->
          <!-- @click="onSave()" -->
          <view
            class="btn primary"
            @click="onSaveHandle()"
            v-if="
              !(
                form.taskId ||
                !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
              ) && checkPremiss('need_rdDemand_add')
            "
          >
            <image src="../../../static/save.png" class="btn-icon"></image>
            保存
          </view>
          <view
            class="btn primary"
            @click="onSubmit()"
            v-if="
              !(
                form.taskId ||
                !(
                  form.id &&
                  (form.status == null || form.status == 0 || form.status == 9 || form.status == 3)
                )
              ) && checkPremiss('need_rdDemand_submit')
            "
          >
            <image src="../../../static/submit.png" class="btn-icon"></image>
            提交
          </view>
          <view
            class="btn primary"
            @click="onRevokeShow()"
            v-if="
              !(form.taskId || !(form.id && form.status == 1)) &&
              checkPremiss('need_rdDemand_revoke')
            "
          >
            <image src="../../../static/rovoke.png" class="btn-icon"></image>
            撤回
          </view>
          <view
            class="btn primary"
            @click="onDel()"
            v-if="
              !(
                form.taskId ||
                !(
                  form.id &&
                  (form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
                )
              ) && checkPremiss('need_rdDemand_del')
            "
          >
            <image src="../../../static/del.png" class="btn-icon"></image>
            删除
          </view>
          <!--   v-if="
              ((form.status == '2' || form.status == '3') &&
                isCanCancelApprover &&
                ((form.rdFlag != '1' &&
                  form.rdFlag != '0' &&
                  (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1')) ||
              (form.instanceId === null &&
                (form.status == '2' || form.status == '3') &&
                ((form.rdFlag != '1' &&
                  form.rdFlag != '0' &&
                  (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1'))
            " -->
          <view
            class="btn primary"
            @click="onCancelApprover()"
            v-if="
              ((form.status == '2' || form.status == '3') &&
                isCanCancelApprover &&
                (form.taskAllStatus == 1 || form.taskAllStatus == 0) &&
                ((form.reviewStatus != '2' && (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1')) ||
              (form.instanceId === null &&
                (form.taskAllStatus == 1 || form.taskAllStatus == 0) &&
                (form.status == '2' || form.status == '3') &&
                ((form.reviewStatus != '2' && (form.autoTask == '0' || form.autoTask == null)) ||
                  form.autoTask == '1'))
            "
          >
            <image src="../../../static/rovoke1.png" class="btn-icon"></image>
            弃审
          </view>
        </view>
      </view>
      <view style="width: 100; height: 10rpx; background-color: transparent"></view>
    </view>

    <leaguerPicker
      :show="selectUserShow"
      :filtration="true"
      :checked="selectList"
      :nop="1"
      :returnDeptName="true"
      @hideModal="hideModal"
      @checkLeaguer="checkLeaguer"
    ></leaguerPicker>

    <pickerCompany
      :show="selectPickerCompany"
      :filtration="true"
      :checked="selectPickerCompanyList"
      :nop="1"
      :returnDeptName="true"
      @hideModal="hidePickerCompanyModal"
      @checkLeaguer="checkPickerCompanyLeaguer"
    ></pickerCompany>
  </view>

  <wd-popup v-model="revokeShow" position="bottom" @close="handleClose">
    <view style="display: flex; flex-direction: column; height: 100%">
      <wd-textarea
        v-model="revokeComment"
        placeholder="请填写撤回原因"
        no-border
        prop="revokeComment"
        class="reovke-textarea"
      />
      <view class="flow-btn-fixed">
        <view class="btn_group" style="width: 100%">
          <view class="btn danger" @click="handleClose">取消</view>
          <view class="btn primary" @click="onRevoke">撤回</view>
        </view>
      </view>
    </view>
  </wd-popup>
  <pickerInvList
    :show="selectpickerInvList"
    :filtration="true"
    :checked="selectpickerInvListList"
    :nop="1"
    :returnDeptName="true"
    @hideModal="hidepickerInvList"
    @checkLeaguer="checkpickerInvList"
  ></pickerInvList>
  <!-- <demandStandardlist
      :show="selectdemandStandardlistShow"
      @checkLeaguer="getdemandStandardlist"
      @hideModal="selectdemandStandardlistShow = false"
      ref="demandStandardlistRef"
    /> -->
  <demandStandardlist @checkLeaguer="getdemandStandardlist" ref="demandStandardlistRef" />
</template>

<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import {
  getObj,
  getPersonByPersonCode,
  getPmDict,
  getBaseDemandType,
  getSequenceNo,
  addObj,
  putObj,
  submitProcess,
  delObj,
  revokeProcess,
  selectTaskByProcessInstanceId,
  completeTask,
  listLastNodePerson,
  reviveProcess,
  selectCheckTarget,
  selectrdDocumentsPostUser,
  baseTrade,
  getDeptByCodeAndTenantId,
} from '@/service/pm-requirement';
import { formatByDayjs, downloadFile } from '@/utils/util';
import { useUserStore } from '@/stores/user';
import { useDict } from '@/hooks/dict';
import flowDetailsTable from '@/task/components/flowDetailsTable.vue';
import cache from '@/utils/cache';
import pickerInvList from '@/components/pickerInvList.vue';
import showModal from '@/utils/modal';
import UniPrintButton from '@/pages/pm/assay-report/component/uniPrintButton.vue';
import ThPrint from '@/pages/pm/assay-report/component/th-print.vue';
import demandStandardlist from './demand-standard-list.vue';
// import assayReport from '@/pages/pm/assay-report/component/assayReport.vue';
import assayReport from './component/fupei-report.vue';

const setting = useSetting();
const minDate = ref(new Date().getTime());
const emits = defineEmits(['refresh']);
const tenantId = cache.getTenant();
const tenantName = cache.get('tenantName');
const tenantCode = cache.get('tenantCode');

const userStore = useUserStore();
const flowDetailsTableRef: any = ref({});
let delrdDemandStandardlist = [];
const rdConnectEntityList = ref([]);

// 提交表单数据
const form = reactive({
  id: null,
  demandDate: null,
  personName: null,
  demandType: null,
  demandTypeCode: null,
  deptHead: null,
  deptCode: null,
  applicationType: null,
  applicationCode: null,
  applicationList: [],
  samplesNum: null,
  demandDesc: null,
  sampleCoding: null,
  askCompleteTime: null,
  taskCode: null,
  userCode: null,
  invName: null,
  invDemand: null,
  sampleFlag: '0',
  demandCode: null,
  cusName: null,
  personCode: null,
  deptHeadCode: null,
  cusFlag: '0',
  demandResult: null,
  completeTime: null,
  // technologyHead: null,
  remark: null,
  // technologyHeadCode: null,
  taskId: null,
  instanceId: null,
  invStd: null,
  invCode: null,
  sampleCode: null,
  sampleBatch: null,
  deptName: null,
  rdFlag: null,
  chiefEngineer: null,
  deputyChiefEngineer: null,
  status: null,
  sampleFlagName: '否',
  deputyChiefEngineerUrl: null,
  chiefEngineerUrl: null,
  sampleUnit: null,
  sampleUnitCode: null,
  requestNumUnit: null,
  requestNumUnitCode: null,
  tenantName: null,
  tenantId: null,
  tenantCode: null,
  cusCode: null,
  deptId: null,
  taskFlag: null,
  // technologyHeadName: null,
  rdProjectUserEntity: [],
  rdDemandFileEntity: [],
  requestFlag: 0,
  requestNum: null,
  rdConnectEntity: [],
  reviewStatus: null,
  wayCode: null,
  reply: null,
  rdTaskFileEntity: [],
  rdReplyFileEntity: [],
  replyFlag: null,
  invEnName: null,
  rdReplyChecksEntityReport: [],
  rdReplyChecksEntityTask: [],
});

const selectrdDocumentsPostUserList = async () => {
  try {
    const res = await selectrdDocumentsPostUser({
      webSql: `documents_code = '1'`,
      size: 1000,
    });
    if (res.code !== 0) {
      return;
    }
    if (
      form.rdProjectUserEntity.length &&
      form.rdProjectUserEntity.find((item) => item.reviewFlag == 1 && item.signatureFlag == 1)
    ) {
      return;
    }
    const l = res.data.records.filter(
      (item) => item.reviewFlag == 1 && item.signatureFlag == 1 && item.chooseFlag == 0,
    );
    l.forEach((item) => {
      form.rdProjectUserEntity.push({
        personId: item.personId,
        userName: item.userName,
        userCode: item.userCode,
        userType: item.documentsPostCode,
        documentsName: item.documentsName,
        documentsCode: item.documentsCode,
        documentsId: item.documentsId,
        documentsPostCode: item.documentsPostCode,
        documentsPostName: item.documentsPostName,
        processCode: 1,
        reviewFlag: item.reviewFlag,
        signatureFlag: item.signatureFlag,
        chooseFlag: item.chooseFlag,
      });
    });
  } catch (err) {}
};

const oldrdDemandStandard = ref([]);
const experimentReportEntity: any = ref({});
const reviewCode = ref('');
const reportRevideData: any = ref({});
const fsReportDetailRef: any = ref({});
const init = (id) => {
  uni.showLoading({
    mask: true,
  });
  getObj({ id })
    .then((res) => {
      console.log('res', res);
      if (res.code == 0) {
        Object.assign(form, res.data);
        experimentReportEntity.value = res.data.experimentReportEntity;
        if (experimentReportEntity.value && experimentReportEntity.value.length) {
          reviewCode.value = experimentReportEntity.value[0].ccode;
          reportreviewCode(reviewCode.value, 2);
        }
        // form.applicationList = res.data.applicationCode.split(',');
        try {
          form.applicationList = res.data.applicationCode.split(',');
        } catch (error) {
          form.applicationList = [];
        }

        // let demandTypeL = [];
        // if (res.data.cusFlag == '1') {
        //   demandTypeL = [
        //     {
        //       value: '4',
        //       label: '新产品',
        //     },
        //     {
        //       value: '5',
        //       label: '工艺改进思路',
        //     },
        //   ];
        // } else {
        //   demandTypeL = [
        //     {
        //       value: '1',
        //       label: '来样定制',
        //       children: [
        //         {
        //           value: '10',
        //           label: '检测分析',
        //         },
        //         {
        //           value: '11',
        //           label: '定制样品',
        //         },
        //       ],
        //     },
        //     {
        //       value: '2',
        //       label: '按指标定制',
        //       children: [
        //         {
        //           value: '20',
        //           label: '确认是否能做',
        //         },
        //         {
        //           value: '21',
        //           label: '提供样品',
        //         },
        //         {
        //           value: '22',
        //           label: '配方验证',
        //         },
        //       ],
        //     },
        //     {
        //       value: '3',
        //       label: '信息咨询',
        //       children: [
        //         {
        //           value: '30',
        //           label: '延长保质期',
        //         },
        //         {
        //           value: '31',
        //           label: '调查问卷',
        //         },
        //       ],
        //     },
        //   ];
        // }

        // demandTypeCascader.value = [demandTypeL];
        setdemandTypeCascader(res.data.cusFlag);

        setTimeout(() => {
          nextTick(() => {
            try {
              const l = res.data.demandType.split(' / ');
              const demandTypeCodeList1 = [];
              const o = demandTypeCascader.value[0].find((d) => d.label == l[0]);
              demandTypeCodeList1.push(o.value);
              if (l.length == 2) {
                const o2 = o.children.find((d) => d.label == l[1]);
                demandTypeCascader.value.push(o.children);
                demandTypeCodeList1.push(o2.value);
              }

              demandTypeCodeList.value = demandTypeCodeList1;
              // demandTypeCodeList.value = ['2', '21'];
            } catch (error) {
              console.log('err', error);
            }
          });
        }, 0);

        form.askCompleteTime = new Date(form.askCompleteTime);
        form.demandDate = new Date(form.demandDate);
        if (res.data.instanceId) {
          selectTaskByProcessInstanceId({
            processInstanceId: res.data.instanceId,
          })
            .then((res) => {
              form.taskId = res.data && res.data.taskId ? res.data.taskId : null;
            })
            .catch(() => {
              form.taskId = null;
            });
          getCancelApprover();
          console.log('form', form);
        }

        if (res.data.rdDemandStandard && res.data.rdDemandStandard.length) {
          isShowCheckTarget.value = true;
          oldrdDemandStandard.value = res.data.rdDemandStandard;
          // 判断有多少行
          // const line = [];
          // res.data.rdDemandStandard.forEach((item) => {
          //   const o = line.find((l) => l == item.standardName);
          //   if (!o) {
          //     line.push(item.standardName);
          //   }
          // });
          // const allList = [];
          // line.forEach((item) => {
          //   const l = res.data.rdDemandStandard.filter((e) => e.standardName == item);
          //   let o = {};
          //   l.forEach((item) => {
          //     o = { ...item, ...o };
          //     if (item.addFlag == 0) {
          //       if (item.standardType == 1) {
          //         o['cchkguidename'] = item.standardName;
          //         o['cchkguidecode'] = item.standardCode;
          //         o['checktarget'] = item.standardValue;
          //       } else {
          //         o['cchkguidename'] = item.standardName;
          //         o['cchkguidecode'] = item.standardCode;
          //         o['cusCheckTarget'] = item.standardValue;
          //       }
          //     } else {
          //       o['cchkguidename'] = item.standardName;
          //       o['cchkguidecode'] = item.standardCode;
          //       o['cusCheckTarget'] = item.standardValue;
          //     }
          //     o['addFlag'] = item.addFlag;
          //     o['id'] = item.id;
          //   });
          //   allList.push(o);
          // });
          // checkTargetList.value = allList;
          checkTargetList.value = res.data.rdDemandStandard
            .filter((item) => item.delFlag != 1)
            .map((item) => {
              return {
                ...item,
                cchkguidename: item.standardName,
                cchkguidecode: item.standardCode,
                checktarget: item.standardValue === null ? '' : item.standardValue,
                cusCheckTarget: item.standardValuePm === null ? '' : item.standardValuePm,
              };
            });
        } else {
          isShowCheckTarget.value = false;
          oldrdDemandStandard.value = [];
        }

        if (checkTargetList.value && checkTargetList.value.length) {
          isShowCheckTarget.value = true;
        } else {
          isShowCheckTarget.value = false;
        }

        if (
          (res.data.demandTypeCode == '42' || res.data.demandTypeCode == '12') &&
          (res.data.status == 0 ||
            res.data.status == null ||
            res.data.status == 3 ||
            res.data.status == 9)
        ) {
          isShowCheckTarget.value = true;
        }

        if (res.data.instanceId) {
          nextTick(() => {
            try {
              flowDetailsTableRef.value && flowDetailsTableRef.value.getFlowDetails();
            } catch (error) {
              console.log('error', error);
            }
          });
        }
        getSampleList(res.data.demandTypeCode, false);

        // 限制样品
        if (res.data.demandTypeCode == '21') {
          requestFlagList.value = defaultrequestFlagList.filter((item) => item.value != 0);
        } else {
          requestFlagList.value = defaultrequestFlagList;
        }
        // requestFlagList.value = defaultrequestFlagList;

        if (!(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)) {
          requestFlagList.value = defaultrequestFlagList;
        }

        if (form.rdConnectEntity && form.rdConnectEntity.length) {
          rdConnectEntityList.value = form.rdConnectEntity.filter((item) => item.delFlag == 0);
        } else {
          rdConnectEntityList.value = [];
        }
      } else {
        uni.showToast({
          mask: true,
          icon: 'none',
          title: `获取数据失败，失败原因${res.msg}`,
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};
onLoad(async (options) => {
  uni.$off('pm-inv');
  console.log('opp', options);
  let customerDemandType = '客户需求';
  if (options.cusFlag == '1') {
    customerDemandType = '非客户需求';
  }
  form.cusFlag = options.cusFlag;
  form.tenantId = tenantId;
  form.tenantName = tenantName;
  form.tenantCode = tenantCode;

  // await getDict(customerDemandType);
  await getDict(options.cusFlag);
  const { id } = options;
  if (id) {
    init(id);
  } else {
    // getDemandCode('need_demandCode');
    form.demandDate = formatByDayjs(new Date(), 'YYYY-MM-DD 00:00:00');
  }
  // selectrdDocumentsPostUserList();
});

// onUnmounted(() => {
//   uni.$off('pm-inv');
// });

const goBack = () => {
  uni.navigateBack();
  uni.$off('pm-inv');
};

const printerVisible = ref(false);
const showPrinter = () => {
  printerVisible.value = !printerVisible.value;
};

const demandTypeList = ref([]);
const applicationTypeList = ref([]);
const sampleUnitList = ref([]);
const { pm_sample_flag } = useDict('pm_sample_flag');
const demandTypeCascader = ref([]);
const demandTypeCodeList = ref([]);
const getDict = async (type) => {
  // await getBaseDemandType({ demandSource: type, pageSize: -1, deleteFlag: 0 }).then((res) => {
  //   demandTypeList.value = res.data.records;
  // });

  // getPmDict({ dictType: 'applicationType', pageSize: -1 }).then((res) => {
  //   applicationTypeList.value = res.data.records;
  // });

  await getapplicationTypeList();

  await getPmDict({ dictType: 'pm_need_unit', pageSize: -1 }).then((res) => {
    sampleUnitList.value = res.data.records;
  });

  // let demandTypeL = [];
  // if (type == '1') {
  //   demandTypeL = [
  //     {
  //       value: '4',
  //       label: '新产品',
  //     },
  //     {
  //       value: '5',
  //       label: '工艺改进思路',
  //     },
  //   ];
  // } else {
  //   demandTypeL = [
  //     {
  //       value: '1',
  //       label: '来样定制',
  //       children: [
  //         {
  //           value: '10',
  //           label: '检测分析',
  //         },
  //         {
  //           value: '11',
  //           label: '定制样品',
  //         },
  //       ],
  //     },
  //     {
  //       value: '2',
  //       label: '按指标定制',
  //       children: [
  //         {
  //           value: '20',
  //           label: '确认是否能做',
  //         },
  //         {
  //           value: '21',
  //           label: '提供样品',
  //         },
  //         {
  //           value: '22',
  //           label: '配方验证',
  //         },
  //       ],
  //     },
  //     {
  //       value: '3',
  //       label: '信息咨询',
  //       children: [
  //         {
  //           value: '30',
  //           label: '延长保质期',
  //         },
  //         {
  //           value: '31',
  //           label: '调查问卷',
  //         },
  //       ],
  //     },
  //   ];
  // }

  // demandTypeCascader.value = [demandTypeL];

  setdemandTypeCascader(type);
};

const getApplicationType = (e) => {
  form.applicationType = e.selectedItems.map((item) => item.value).join(',');
  form.applicationCode = e.selectedItems.map((item) => item.label).join(',');
};

const getDemandCode = (tableName) => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  uni.showLoading({
    mask: true,
  });
  getSequenceNo({ tableName })
    .then((res) => {
      if (tableName == 'need_demandCode') {
        // form.demandCode = res.data;
        if (form.cusFlag == '0') {
          form.demandCode = `CD${res.data}`;
        } else {
          form.demandCode = `DE${res.data}`;
        }
      } else if (tableName == 'need_sampleCode') {
        form.sampleCode = `YP${res.data}`;
      } else if (tableName == 'need_sampleBatch') {
        form.sampleBatch = `PC${res.data}`;
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const selectUserShow = ref(false);
const selectList = ref([]);
const hideModal = () => {
  selectUserShow.value = false;
};
const checkLeaguer = (e) => {
  form.personCode = e[0].personCode;
  form.personName = e[0].personName;
  form.deptName = e[0].deptName;
  // form.deptCode = e.row.deptCode;
  form.deptCode = e[0].deptId;
  form.deptId = e[0].deptId;
};
const showSelectUser = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  selectUserShow.value = true;
};

// 选择客户
const selectPickerCompany = ref(false);
const selectPickerCompanyList = ref([]);
const tenantTreeId = ref('');
const hidePickerCompanyModal = () => {
  selectPickerCompany.value = false;
};

const getPersonByPersonCodeHandle = (cusPerson, tenantId) => {
  getPersonByPersonCode({
    personCode: cusPerson,
    tenantId,
    currentFlag: 1,
  }).then((res) => {
    // form.personName = res.data.personName;
    // form.personCode = res.data.personCode;

    const { hrPersonDeptList } = res.data;
    const o = hrPersonDeptList.find(
      (item) => item.mainDeptFlag == '1' && item.tenantId == tenantId,
    );
    form.deptId = o.deptId;
    form.deptName = o.deptName;
    form.deptCode = o.deptId;
  });
};

const checkPickerCompanyLeaguer = (e) => {
  const { cusPerson } = e[0];
  form.cusName = e[0].cusName;
  form.cusCode = e[0].cusCode;
  form.tenantId = e[0].tenantId;
  form.tenantName = e[0].tenantName;
  form.tenantCode = e[0].tenantCode;
  tenantTreeId.value = e[0].tenantId;
  const { cusDeptCode } = e[0];
  const { cusDeptName } = e[0];
  form.personName = e[0].personName;
  form.personCode = e[0].cusPerson;
  if (!cusPerson) return;
  // getPersonByPersonCode({
  //   personCode: cusPerson,
  //   tenantId: e[0].tenantId,
  //   currentFlag: 1,
  // }).then((res) => {
  //   form.personName = res.data.personName;
  //   form.personCode = res.data.personCode;

  //   const hrPersonDeptList = res.data.hrPersonDeptList;
  //   const o = hrPersonDeptList.find(
  //     (item) => item.mainDeptFlag == '1' && item.tenantId == e[0].tenantId,
  //   );
  //   form.deptId = o.deptId;
  //   form.deptName = o.deptName;
  //   form.deptCode = o.deptId;
  // });

  if (cusDeptCode) {
    getDeptByCodeAndTenantId({
      deptCode: cusDeptCode,
      tenantId: e[0].tenantId,
    })
      .then((res) => {
        const data1 = res;
        form.deptId = data1.deptId;
        form.deptName = data1.name;
        form.deptCode = data1.deptId;
      })
      .catch((err) => {
        getPersonByPersonCodeHandle(cusPerson, e[0].tenantId);
      });
  } else {
    getPersonByPersonCodeHandle(cusPerson, e[0].tenantId);
  }
};
const showSelectPickerCompany = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  selectPickerCompany.value = true;
};

// 是否外来杨
const changesampleFlagName = (e, label = null, type = 0) => {
  form.sampleFlagName = type == 1 ? label : e.selectedItems.label;
  const v = type == 1 ? e : e.value;
  if (v != '0') {
    getDemandCode('need_sampleCode');
    getDemandCode('need_sampleBatch');
  }
  // 默认单位
  if (!form.sampleUnit) {
    form.sampleUnit = 'g';
    form.sampleUnitCode = 'g';
  }
};

//
const changeRequestFlag = () => {
  if (!form.requestNumUnit) {
    form.requestNumUnit = 'g';
    form.requestNumUnitCode = 'g';
  }
};

const rules: any = computed(() => {
  return {
    demandDate: [
      {
        required: true,
        message: '日期不能为空',
      },
    ],
    cusName: [
      {
        // required: true,
        required: form.cusFlag == '0',
        message: '客户不能为空',
      },
    ],
    personName: [
      {
        required: true,
        message: `${form.cusFlag == '0' ? '业务员' : '需求人'}不能为空`,
      },
    ],
    demandType: [{ required: true, message: '需求类型不能为空' }],
    invName: [{ required: true, message: '需求产品不能为空' }],
    invStd: [{ required: true, message: '产品规格不能为空' }],
    applicationType: [{ required: form.cusFlag == '0', message: '用途不能为空' }],
    invDemand: [{ required: form.cusFlag == '0', message: '年需求量/吨不能为空' }],
    sampleFlag: [{ required: true, message: '是否有外来样不能为空' }],
    sampleCode: [{ required: form.sampleFlag != '0', message: '外来样样品编码不能为空' }],
    samplesNum: [
      { required: form.sampleFlag != '0', message: '外来样样品数量不能为空' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.sampleUnitCode || form.sampleFlag == '0') {
            return Promise.resolve();
          }
          return Promise.reject('请选择单位');
        },
      },
    ],
    sampleBatch: [{ required: form.sampleFlag != '0', message: '外来样批次不能为空' }],
    askCompleteTime: [{ required: true, message: '要求完成时间不能为空' }],
    demandDesc: [{ required: true, message: '需求描述不能为空' }],
    requestNum: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (form.requestFlag == 0 || form.requestFlag == null) {
            return Promise.resolve();
          }
          if (form.requestNum === '' || form.requestNum === null) {
            return Promise.reject('请输入给客户提供样品数量');
          }
          return Promise.resolve();
        },
      },
    ],
  };
});

const onCancel = () => {
  uni.navigateBack({});
};
const formRef: any = ref({});

const onSaveHandle = () => {
  // 复配判断选没选需求指标
  if (
    (form.demandTypeCode == '42' || form.demandTypeCode == '12') &&
    checkTargetList.value.filter((item) => item.cchkguidename).length == 0
  ) {
    showModal({
      title: '提示',
      // content: '确认没有检验指标吗',
      content: '需求指标不能为空',
      showCancel: false,
      confirmText: '确定',
      confirm: () => {
        // onSave();
      },
    });
  } else if (
    (form.tenantCode == 'UFDATA_102_2016' || form.tenantCode == 'UFDATA_103_2016') &&
    !form.invEnName
  ) {
    showModal({
      title: '提示',
      content: '产品英文名称没有输入，确定不输入吗？',
      showCancel: true,
      confirm: () => {
        onSave();
      },
    });
  } else {
    onSave();
  }
};

const onSave = (isSubmit = false) => {
  formRef.value.validate().then(({ valid, errors }) => {
    if (!valid) return false;

    let rdDemandStandard = [];
    // if (checkTargetList.value && checkTargetList.value.length) {
    rdDemandStandard = checkTargetList.value.map((item) => {
      return {
        ...item,
        standardCode: item.cchkguidecode,
        standardName: item.cchkguidename,
        standardValue: item.checktarget,
        standardValuePm: item.cusCheckTarget,
      };
    });
    let delList = [];
    delrdDemandStandardlist.forEach((item) => {
      const o = delCheckTargetList.value.find((d) => item.id == d.id);
      if (!o) {
        delList.push(item);
      }
    });
    delList = delList.concat(delCheckTargetList.value);
    rdDemandStandard = rdDemandStandard.concat(delList);
    // }

    // rdDemandStandard = rdDemandStandard.concat(delCheckTargetList.value);
    rdDemandStandard = rdDemandStandard.map((item) => {
      return {
        ...item,
        demandCode: form.demandCode,
        tenantId,
      };
    });

    // const delrdDemandStandardlist = [];
    // if (oldrdDemandStandard.value && oldrdDemandStandard.value.length) {
    //   oldrdDemandStandard.value.forEach((item) => {
    //     const o = rdDemandStandard.find(
    //       (r) =>
    //         r.cchkguidecode &&
    //         r.cchkguidecode == item.standardCode &&
    //         r.standardValue == item.standardValue &&
    //         item.id == r.id,
    //     );
    //     if (!o) {
    //       delrdDemandStandardlist.push({
    //         ...item,
    //         delFlag: 1,
    //       });
    //     }
    //   });
    // }

    // rdDemandStandard = rdDemandStandard.concat(delrdDemandStandardlist);
    rdDemandStandard = rdDemandStandard.filter((item) => item.standardName);

    const params = {
      ...form,
      sampleCode: form.sampleFlag != '0' ? form.sampleCode : '',
      samplesNum: form.sampleFlag != '0' ? form.samplesNum : 0,
      sampleBatch: form.sampleFlag != '0' ? form.sampleBatch : '',
      askCompleteTime: form.askCompleteTime
        ? formatByDayjs(form.askCompleteTime, 'YYYY-MM-DD HH:mm:ss')
        : '',
      demandDate: form.demandDate ? formatByDayjs(form.demandDate, 'YYYY-MM-DD HH:mm:ss') : '',
      rdDemandStandard,
      requestNumUnit: form.requestFlag != 0 ? form.requestNumUnit : '',
      requestNum: form.requestFlag != 0 ? form.requestNum : 0,
      sampleUnit: form.sampleFlag != '0' ? form.sampleUnit : '',
      sampleUnitCode: form.sampleFlag != '0' ? form.sampleUnitCode : '',
    };

    params.rdDemandFileEntity = params.rdDemandFileEntity.map((item) => {
      return {
        // ...item,
        fileName: item.fileName,
        fileUrl: item.fileUrl,
        demandCode: params.demandCode,
        tenantId: tenantTreeId.value,
      };
    });

    params.rdProjectUserEntity = params.rdProjectUserEntity.map((item) => {
      return {
        ...item,
        demandCode: params.demandCode,
        tenantId: tenantTreeId.value,
        rdCode: params.demandCode,
      };
    });

    // if (form.demandTypeCode != '21' && form.demandTypeCode != '22' && form.demandTypeCode != '11') {
    //   params['requestFlag'] = 0;
    // }

    if (params.requestFlag == 0) {
      params.requestNum = 0;
      params.requestNumUnitCode = '';
      params.requestNumUnit = '';
      if (params.rdConnectEntity) {
        params.rdConnectEntity = params.rdConnectEntity.map((item) => {
          return {
            ...item,
            delFlag: 1,
          };
        });
      }
    }

    uni.showLoading({
      mask: true,
    });

    (form.id ? putObj(params) : addObj(params))
      .then((res) => {
        // uni.navigateBack();
        if (res.code == 0) {
          if (isSubmit) {
            submitHandle();
          } else {
            uni.hideLoading();
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}保存成功`,
              icon: 'none',
            });
            init(form.id || res.data.id);
          }
        } else {
          uni.hideLoading();
          uni.showToast({
            mask: true,
            title: `单据${form.demandCode}保存失败，失败原因${res.msg}`,
            icon: 'none',
          });
        }
      })
      .catch((err) => {
        uni.hideLoading();
      })
      .finally(() => {
        // uni.hideLoading();
      });
  });
};

const getSampleUnit = (e) => {
  form.sampleUnitCode = e.selectedItems.label;
  form.sampleUnit = e.value;
};

const getRequestNumUnit = (e) => {
  form.requestNumUnitCode = e.selectedItems.label;
  form.requestNumUnit = e.value;
};

const changedemandType = (e) => {
  form.demandType = e.selectedItems.demandName;
};

const onSubmit = () => {
  // 复配判断选没选需求指标
  if (
    (form.demandTypeCode == '42' || form.demandTypeCode == '12') &&
    checkTargetList.value.filter((item) => item.cchkguidename).length == 0
  ) {
    showModal({
      title: '提示',
      // content: '确认没有检验指标吗',
      content: '需求指标不能为空',
      showCancel: false,
      confirmText: '确定',
      confirm: () => {
        // onSave();
      },
    });
  } else if (
    (form.tenantCode == 'UFDATA_102_2016' || form.tenantCode == 'UFDATA_103_2016') &&
    !form.invEnName
  ) {
    showModal({
      title: '提示',
      content: '产品英文名称没有输入，确定不输入吗？',
      showCancel: true,
      confirm: () => {
        onSave(true);
      },
    });
  } else {
    showModal({
      title: '提示',
      content: '是否提交该单据',
      showCancel: true,
      confirm: () => {
        onSave(true);
      },
    });
  }
};

const submitHandle = () => {
  // uni.showModal({
  //   title: '提示',
  //   content: '是否提交该单据',
  //   showCancel: true,
  //   success: ({ confirm, cancel }) => {
  //     if (confirm) {
  //       uni.showLoading({
  //         mask: true,
  //       });
  //       submitProcess(form.id)
  //         .then((res) => {
  //           if (res.code == 0) {
  //             uni.showToast({
  //               mask: true,
  //               title: `单据${form.demandCode}提交成功`,
  //               icon: 'none',
  //             });
  //             init(form.id);
  //           } else {
  //             uni.showToast({
  //               mask: true,
  //               title: `单据${form.demandCode}提交失败，失败原因：${res.msg}`,
  //               icon: 'none',
  //             });
  //           }
  //         })
  //         .finally(() => {
  //           uni.hideLoading();
  //         });
  //     }
  //   },
  // });

  uni.showLoading({
    mask: true,
  });
  submitProcess(form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          mask: true,
          title: `单据${form.demandCode}提交成功`,
          icon: 'none',
        });
        init(form.id);
      } else {
        uni.showToast({
          mask: true,
          title: `单据${form.demandCode}提交失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const onDel = () => {
  showModal({
    title: '提示',
    content: '是否删除该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      delObj([form.id])
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}删除成功`,
              icon: 'none',
            });
            // const pages = getCurrentPages();
            // const prevPage = pages[pages.length - 2]; // 上一个页面
            // prevPage.$vm.refresh();
            goBack();
            uni.$emit('refresh');
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}删除失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};

// 撤回
const revokeComment = ref('');
const revokeShow = ref(false);
const handleClose = () => {
  revokeShow.value = false;
};
const onRevoke = () => {
  showModal({
    title: '提示',
    content: '是否撤回该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      revokeProcess({
        id: form.id,
        instanceId: form.instanceId,
        comment: revokeComment.value,
      })
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回成功`,
              icon: 'none',
            });
            handleClose();
            init(form.id);
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};
const onRevokeShow = () => {
  revokeShow.value = true;
};

// 审核信息
const comment = ref('');
const oncomplete = (type) => {
  if (type == '1' && !comment.value) {
    uni.showToast({
      title: '请填写审核意见',
      icon: 'none',
      mask: true,
    });
    return;
  }

  const params = {
    // ...form,
    taskId: form.taskId,
    comment: comment.value,
    id: form.id,
    approve: type == 0,
  };
  uni.showLoading({
    mask: true,
  });
  completeTask(params, form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '单据审核成功',
          icon: 'none',
          mask: true,
        });
        // uni.navigateBack({});
        form.instanceId = '';
        init(form.id);
        uni.$emit('refresh');
        // nextTick(() => {
        //   flowDetailsTableRef.value.getFlowDetails();
        // });
      } else {
        uni.showToast({
          mask: true,
          title: `单据审核失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const isCanCancelApprover = ref(false); // 是否能弃审
const getCancelApprover = () => {
  listLastNodePerson({
    processInstanceId: form.instanceId,
  })
    .then((res) => {
      const dataList = res.data;
      const { username } = userStore.userInfos.user;
      if (dataList.find((item) => item == username)) {
        isCanCancelApprover.value = true;
      } else {
        isCanCancelApprover.value = false;
      }
    })
    .finally(() => {});
};

const onCancelApprover = () => {
  showModal({
    title: '提示',
    content: '是否弃审该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      reviveProcess(form.id)
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}弃审成功`,
              icon: 'none',
            });
            form.instanceId = '';
            init(form.id);
            // nextTick(() => {
            //   flowDetailsTableRef.value.getFlowDetails();
            // });
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}弃审失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};

const searchInvList = () => {
  if (
    form.taskId ||
    !(form.status == 0 || form.status == null || form.status == 3 || form.status == 9)
  ) {
    return;
  }
  // selectpickerInvList.value = true;
  uni.$on('pm-inv', (e) => {
    console.log('sign', e);
    getInv(e);
  });
  uni.navigateTo({
    url: '/pages/pm/requirement/check-inv',
  });
};

const checkTargetList = ref([]);
const isShowCheckTarget = ref(false);
const getInv = (e) => {
  uni.$off('pm-inv');
  form.invName = e.cinvname;
  form.invStd = e.cinvstd;
  form.invCode = e.cinvcode;
  form.invEnName = e.cenglishName;
  uni.showLoading({
    mask: true,
  });
  isShowCheckTarget.value = true;
  selectCheckTarget({
    cinvcode: e.cinvcode,
    tenantId,
  })
    .then((res) => {
      if (res.code === 0) {
        const l = checkTargetList.value
          .filter((item) => item.id)
          .map((item) => {
            return {
              ...item,
              delFlag: 1,
            };
          });

        delrdDemandStandardlist = delrdDemandStandardlist.concat(l);

        checkTargetList.value = res.data.map((item) => {
          return {
            ...item,
            addFlag: '0',
            // cusCheckTarget: '',
            cusCheckTarget: item.checktarget,
          };
        });
      } else {
        checkTargetList.value = [];
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    })
    .catch((err) => {
      checkTargetList.value = [];
      uni.showToast({
        title: err.msg,
        icon: 'none',
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 选择客户
const selectpickerInvList = ref(false);
const selectpickerInvListList = ref([]);
const hidepickerInvList = () => {
  selectpickerInvList.value = false;
};
const checkpickerInvList = (e) => {
  form.invName = e.invName;
  form.invStd = e.invStd;
  form.invCode = e.cinvcode;
  form.invEnName = e.cenglishName;
};

const addCheckTargetList = () => {
  checkTargetList.value.push({
    // cchkguidename: null,
    // addFlag: '1',
    // checktarget: null,
    // cusCheckTarget: null,
    cchkguidename: '',
    addFlag: '1',
    checktarget: '',
    cusCheckTarget: '',
  });
};

const delCheckTargetList = ref([]);
const delRow = (index, item) => {
  if (checkTargetList.value.length > 0) {
    showModal({
      title: '提示',
      content: '是否删除该需求指标',
      showCancel: true,
      confirm: () => {
        if (item.id) {
          const o = delCheckTargetList.value.find((i) => item.id == i.id);
          if (!o) {
            delCheckTargetList.value.push({
              ...item,
              delFlag: 1,
            });
          }
        }
        checkTargetList.value.splice(index, 1);
      },
    });
  }
};

const uploadComplete = (ref: any) => {
  const { id, fileName, url, fileType } = ref;
  console.log({
    id,
    fileName,
    url,
    fileType,
  });

  form.rdDemandFileEntity.push({
    fileName,
    fileUrl: url,
  });

  console.log('rdDemandFileEntity', form.rdDemandFileEntity);
};

const previewFileHandle = (file) => {
  uni.navigateTo({
    url: `/pages/pm/preview-online?url=${file}`,
  });
};

const removeFile = (index) => {
  showModal({
    title: '提示',
    content: '是否删除该附件',
    showCancel: true,
    confirm: () => {
      form.rdDemandFileEntity.splice(index, 1);
    },
  });
};

const columnChangedemandTypeCodeList = ({ selectedItem, resolve, finish }) => {
  setTimeout(() => {
    if (selectedItem.children && selectedItem.children.length) {
      resolve(selectedItem.children);
    } else {
      // 没有下一项时，执行完成
      finish();
    }
  }, 300);
};

const handleConfirmdemandTypeCodeList = (e) => {
  const { value } = e;
  const { selectedItems } = e;
  const o = selectedItems[selectedItems.length - 1];
  const demandTypeCode = o.value;
  form.demandTypeCode = demandTypeCode;
  // form.demandType = o['label'];
  form.demandType = e.selectedItems.map((item) => item.label).join(' / ');
  getSampleList(demandTypeCode);

  //  判断是否提供样品
  if (demandTypeCode == '21') {
    requestFlagList.value = defaultrequestFlagList.filter((item) => item.value != 0);
    // requestFlagList.value = defaultrequestFlagList;
    form.requestFlag = 1;
    if (!form.requestNumUnit) {
      form.requestNumUnit = 'g';
      form.requestNumUnitCode = 'g';
    }
  } else {
    requestFlagList.value = defaultrequestFlagList;
    form.requestFlag = 0;
  }

  if (demandTypeCode == '43') {
    form.sampleFlag = '2';
    changesampleFlagName('2', '稀释', 1);
  }

  if (demandTypeCode == '42' || demandTypeCode == '12') {
    isShowCheckTarget.value = true;
  } else if (!form.invCode) {
    const l = checkTargetList.value
      .filter((item) => item.id)
      .map((item) => {
        return {
          ...item,
          delFlag: 1,
        };
      });
    delrdDemandStandardlist = delrdDemandStandardlist.concat(l);

    checkTargetList.value = [];
    isShowCheckTarget.value = false;
  }
};
const displayFormat = (selectedItems) => {
  if (selectedItems && selectedItems.length) {
    // return (
    //   selectedItems[selectedItems.length - 2].label +
    //   ' / ' +
    //   selectedItems[selectedItems.length - 1].label
    // );

    const l = selectedItems.map((item) => item.label);
    return l.join(' / ');
  }
  return null;
};

const samplaFlagList = ref([]);
const getSampleList = (demandTypeCode, isSetData = true) => {
  if (demandTypeCode == '10' || demandTypeCode == '11' || demandTypeCode == '12') {
    // 样品
    samplaFlagList.value = pm_sample_flag.value.filter((item) => item.value != 0);
  } else if (demandTypeCode == '4' || demandTypeCode == '5' || demandTypeCode == '22') {
    // 样品
    samplaFlagList.value = pm_sample_flag.value;
  } else {
    // samplaFlagList.value = pm_sample_flag.value.filter((item) => item.value == 0);
    samplaFlagList.value = pm_sample_flag.value;
  }
  if (isSetData) {
    let val = samplaFlagList.value[0].value;
    let { label } = samplaFlagList.value[0];

    if (demandTypeCode == '12') {
      try {
        val = samplaFlagList.value[1].value;
        label = samplaFlagList.value[1].label;
      } catch (error) {
        val = '2';
        label = '水样';
      }
    } else {
      val = samplaFlagList.value[0].value;
    }

    form.sampleFlag = val;
    changesampleFlagName(val, label, 1);
  }
};

const defaultrequestFlagList = [
  {
    label: '是',
    value: 1,
  },
  {
    label: '否',
    value: 0,
  },
];

const requestFlagList = ref([
  {
    value: 0,
    label: '否',
  },
  {
    value: 1,
    label: '是',
  },
]);

const checkPremiss = (k) => {
  return userStore.userInfos.authBtnList.some((v: string) => v === k);
};

// 处理数据转换为树形
// const transformTree = (data, len = 2, parent = '') => {
//   const newTree = [];
//   data.map((item) => {
//     if (
//       (parent &&
//         item.tradeCode.substr(0, parent.length) === parent &&
//         item.tradeCode.length === Number(len)) ||
//       (item.tradeCode.length == len && parent === '')
//     ) {
//       newTree.push({
//         tradeCode: item.tradeCode,
//         tradeName: `${item.tradeName}`,
//         tradeGrade: item.tradeGrade,
//         children: transformTree(data, len + 2, item.tradeCode),
//       });
//     }
//   });
//   return newTree;
// };

const transformTree = (data, len = 2, parent = '', ll = []) => {
  const newTree = [];
  data.map((item) => {
    if (
      (parent &&
        item.tradeCode.substr(0, parent.length) === parent &&
        item.tradeCode.length === Number(len)) ||
      (item.tradeCode.length == len && parent === '')
    ) {
      newTree.push({
        tradeCode: item.tradeCode,
        tradeName: `${item.tradeName}`,
        tradeGrade: item.tradeGrade,
        children: transformTree(data, len + 2, item.tradeCode),
      });
    }
  });
  return newTree;
};

const getEndTree = (data) => {
  let l = [];
  data.forEach((item) => {
    if (!(item.children && item.children.length)) {
      l.push(item);
    } else {
      l = l.concat(getEndTree(item.children));
    }
  });

  return l;
};

const getapplicationTypeList = () => {
  baseTrade({
    current: 1,
    size: 1000,
  })
    .then((res) => {
      if (res.code != 0) {
        uni.showToast({
          mask: true,
          title: `获取用途数据失败， 失败原因：${res.msg}`,
          icon: 'none',
        });
        return;
      }
      // applicationTypeList.value = res.data.records.map((item) => {
      //   return {
      //     value: item.tradeName,
      //     label: item.tradeCode,
      //   };
      // });

      const i = transformTree(res.data);
      const l = getEndTree(i);

      // applicationTypeList.value = res.data.map((item) => {
      //   return {
      //     value: item.tradeName,
      //     label: item.tradeCode,
      //   };
      // });

      applicationTypeList.value = l.map((item) => {
        return {
          value: item.tradeName,
          label: item.tradeCode,
        };
      });
    })
    .catch((err) => {
      uni.showToast({
        mask: true,
        title: `获取用途数据失败， 失败原因：${err.msg || err}`,
        icon: 'none',
      });
    });
};

const setdemandTypeCascader = (type) => {
  let demandTypeL = [];
  if (type == '1') {
    demandTypeL = [
      {
        value: '4',
        label: '新产品',
      },
      {
        value: '5',
        label: '工艺改进思路',
      },
    ];
  } else {
    demandTypeL = [
      {
        value: '1',
        label: '来样定制',
        children: [
          {
            value: '10',
            label: '检测分析',
          },
          {
            value: '11',
            label: '定制样品',
          },
          {
            value: '12',
            label: '水样检测',
          },
        ],
      },
      {
        value: '2',
        label: '按指标定制',
        children: [
          {
            value: '20',
            label: '确认是否能做',
          },
          {
            value: '21',
            label: '提供样品',
          },
        ],
      },
      {
        value: '3',
        label: '信息咨询',
        children: [
          {
            value: '30',
            label: '延长保质期',
          },
          {
            value: '31',
            label: '调查问卷',
          },
          {
            value: '32',
            label: '业务咨询',
          },
        ],
      },
      {
        value: '4',
        label: '配方验证',
        children: [
          {
            value: '41',
            label: '合成',
          },
          {
            value: '42',
            label: '复配',
          },
          {
            value: '43',
            label: '稀释',
          },
        ],
      },
    ];
  }

  demandTypeCascader.value = [demandTypeL];
};

const changeInv = (e) => {
  if (e.value == '') {
    const l = checkTargetList.value
      .filter((item) => item.id)
      .map((item) => {
        return {
          ...item,
          delFlag: 1,
        };
      });
    delrdDemandStandardlist = delrdDemandStandardlist.concat(l);
    if (form.demandTypeCode != '42' && form.demandTypeCode != '12') {
      isShowCheckTarget.value = false;
    }
    checkTargetList.value = [];
    form.invStd = '';
    form.invCode = '';
    form.invEnName = '';
  }
};

const downloadFileHandle = (src, name) => {
  name = name.split('.')[0];
  downloadFile(src, name);
};

const selectdemandStandardlistShow = ref(false);
const demandStandardlistRef: any = ref({});
const getdemandStandardlist = (data) => {
  // const parentIndex = data.parentIndex;
  // checkTargetList.value[parentIndex] = {
  //   ...checkTargetList.value[parentIndex],
  //   cchkguidename: data.analysisIndex,
  //   cchkguidecode: data.indexCode,
  // };
  let nList = data.selectList;
  nList = nList.filter((item) => {
    const o = checkTargetList.value.find((c) => item.indexCode === c.cchkguidecode);
    if (o) {
      return false;
    }
    return true;
  });

  const selectList = nList.map((item) => {
    return {
      cchkguidename: item.analysisIndex,
      cchkguidecode: item.indexCode,
      addFlag: '1',
      checktarget: '',
      cusCheckTarget: '',
    };
  });
  const { parentIndex } = data;

  if (selectList && selectList.length) {
    const f = selectList[0];
    const { cchkguidename } = f;
    const { cchkguidecode } = f;
    console.log('checkTargetList', checkTargetList.value);
    const l = [];
    const fullData = checkTargetList.value;
    Object.assign(l, fullData);
    l[parentIndex] = {
      ...l[parentIndex],
      cchkguidename,
      cchkguidecode,
    };

    const sList = selectList.slice(1);
    sList.forEach((item) => {
      const d = item;
      l.splice(parentIndex + 1, 0, d);
    });

    checkTargetList.value = l;
  }
};

const clickcchkguidename = (item, index) => {
  if (item.addFlag == 0) return;
  // selectdemandStandardlistShow.value = true;
  demandStandardlistRef.value.init({ index });
};

const statusList = [
  {
    text: '未提交',
    value: '0',
    color: '#108ee9',
  },
  {
    text: '审批中',
    value: '1',
    color: '#d46b08',
  },
  {
    text: '已审核',
    value: '2',
    color: '#87d068',
  },
  {
    text: '驳回',
    value: '3',
    color: '#f50',
  },
  {
    text: '撤回',
    value: '9',
    color: '#f50',
  },
];
const { bill_status } = useDict('bill_status');
const getStatus = (status) => {
  if (status == null)
    return {
      text: '未提交',
      value: '0',
      color: '#108ee9',
    };
  const o1 = statusList.find((item) => item.value == status);
  const o = bill_status.value.find((item) => item.value == status);
  return o
    ? {
        ...o,
        color: o1.color,
      }
    : { text: status };
};

const reportreviewCode = (e, type) => {
  let ccode = '';
  if (type == 1) {
    ccode = e.value;
  } else {
    ccode = e;
  }
  const o = experimentReportEntity.value.find((item) => item.ccode == ccode);
  reportRevideData.value = o;
  if (o) {
    setReportByReviewCode(o.checkReportId);
  }
};

const setReportByReviewCode = (checkReportId) => {
  if (!checkReportId) return;
  try {
    nextTick(() => {
      fsReportDetailRef.value.getccReportInfo({ id: checkReportId }, true);
    });
  } catch (err: any) {
    console.log('err', err);
  }
};
</script>

<style lang="scss" scoped>
@import '../experiment/components/table';

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx;

  .pm-title {
    box-sizing: border-box;
    padding-left: 20rpx;
    margin: 40rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-left: 8rpx solid #2e5cf6;
    border-radius: 4rpx;
  }

  .pm-row {
    display: flex;
    min-height: 60rpx;
    border-bottom: 1px solid #f6f0f0;

    .pm-label {
      display: flex;
      align-items: center;
      width: 20%;
      font-size: 26rpx;
      color: #979494;
    }

    .pm-value {
      display: flex;
      flex: 1;
      align-items: center;
      font-size: 26rpx;
      color: #333;
    }
  }
}

.sign-main {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // width: 100%;
  // margin: 20rpx 0;
  position: fixed;
  right: 0rpx;
  bottom: 40rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: white;
  text-align: center;
  background-color: rgb(77 128 240);

  // border-radius: 50%;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
}

:deep(.label) {
  width: 160rpx !important;
}

.result-tag {
  padding: 6rpx 14rpx;
  font-size: 24rpx;
  color: white;
  background-color: #87d068;
  border-radius: 4rpx;
}

:deep(.wd-picker__cell) {
  padding: 0 !important;

  // padding: 0 20rpx !important;
  // font-size: 26rpx !important;
}

:deep(.wd-select-picker__cell) {
  padding: 0 !important;
}

// .wd-picker__value-wraper {
//   .wd-icon {
//     display: none !important;
//   }
// }

.seq-no-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.flow-btn-fixed {
  width: 100%;
  background-color: white;
  border-top: 1px solid #f2f2f1;
}

.btn_group {
  display: flex;
  justify-content: space-between;

  // margin: 0rpx 0 20rpx;
  // border-bottom: 1px solid #f2f2f1;

  .btn {
    display: flex;

    // width: 49%;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    // height: 40px;
    min-height: 40px;
    padding: 10rpx 0;
    font-size: 24rpx;
    color: black;

    // background-color: white !important;
    background-color: #dbecff !important;
    border-left: 1px solid #f7f7f7;
    border-radius: 0 !important;

    // color: white;
    border-radius: 6rpx;

    .btn-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;
    }
  }

  .danger {
    background-color: #f56c6c;
  }

  .primary {
    background-color: #409eff;
  }
}

.form-demandDesc {
  align-items: flex-start !important;
}
</style>
<style lang="scss">
/* .sample-unit-class {
      color: #9d9999 !important;
    
      .wd-icon {
        display: none !important;
      }
    
      .wd-picker__placeholder {
        margin-right: 0 !important;
        font-size: 20rpx !important;
        color: #9d9999 !important;
      }
    
      .wd-picker__value {
        margin-right: 0 !important;
        font-size: 20rpx !important;
        color: #9d9999 !important;
      }
    
      .wd-picker__arrow {
        display: none !important;
      }
    } */

.wd-picker,
.wd-select-picker {
  width: 100%;
}

.wd-textarea::after {
  height: 0;
}

:deep(.wd-picker__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

:deep(.wd-input__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

:deep(.wd-textarea__placeholder) {
  font-size: 28rpx !important;
  color: #bfbfbf !important;
}

.sample-unit-custom-value-class .wd-picker__placeholder {
  font-size: 20rpx !important;
  color: #bfbfbf !important;
}

.sample-unit-class {
  .wd-picker__placeholder {
    margin-right: 0 !important;
    font-size: 24rpx !important;
  }

  .wd-icon {
    display: none !important;
  }
}

:deep(.wd-picker__value) {
  color: #262626 !important;
}

:deep(.uni-input-input) {
  color: #262626 !important;
}

:deep(.wd-select-picker__value) {
  color: #262626 !important;
}

:deep(.uni-textarea-compute) {
  div {
    color: #262626 !important;
  }

  color: #262626 !important;
}

:deep(.uni-textarea-textarea) {
  color: #262626 !important;
}

:deep(.wd-textarea.is-auto-height::after) {
  display: none;
}

.reovke-textarea {
  box-sizing: border-box;
  flex: 1 !important;
  padding: 20rpx !important;

  :deep(.wd-textarea__value) {
    height: 100% !important;
  }
}

:deep(.wd-textarea.is-not-empty:not(.is-disabled)::after) {
  background-color: transparent !important;
}

.text {
  word-break: break-all;
  word-wrap: break-word;
}

.title_box .title_text {
  padding-left: 0 !important;
  margin-top: 10rpx !important;
}

.form-file {
  flex-direction: column;

  .label {
    width: 3rem !important;
  }

  .form-file-view {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 100%;

    uni-button {
      margin: 5rpx 0 !important;
    }
  }

  // .content {
  //   flex: 1;
  //   width: 0;
  //   word-break: break-all;
  // }
}

.info-row-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 6rpx 0;
  color: blue;
  word-break: break-all;
}

:deep(.wd-col-picker__cell) {
  padding: 0 !important;
}

.line-red td {
  background-color: #ffecec !important;
}

.table-container table td {
  padding: 0 10rpx !important;

  .wd-textarea__value {
    padding-right: 0 !important;
    background: transparent !important;
  }
}

.assay-report-content {
  .block {
    .content {
      padding: 0 !important;
    }
  }
}

.print {
  position: relative;

  .icon {
    display: flex;
    item-align: center;
    color: #fff;
  }

  &:active {
    background: rgb(0 0 0 / 0%);
  }

  .list {
    position: absolute;
    top: 100rpx;
    right: 0;
    width: 200rpx;
    background: #fff;
    border-radius: 10rpx;
    box-shadow: 0 0 10rpx 5rpx #f1f1f1;

    view {
      border-bottom: 1rpx solid #f1f1f1;

      &:last-child {
        border: none;
      }
    }
  }
}

:deep(.wd-navbar__right--hover) {
  background: none !important;
}
</style>
